package com.imyuanma.qingyun.common.config.security;

import com.imyuanma.qingyun.common.model.ECommonResultCode;
import com.imyuanma.qingyun.common.model.response.Result;
import com.imyuanma.qingyun.common.util.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 会话验证失败处理器
 *
 * @author wangjy
 * @date 2022/07/10 23:36:23
 */
@Component
public class DefaultSessionAuthFailureHandler implements AuthenticationFailureHandler {
    private static final Logger logger = LoggerFactory.getLogger(DefaultSessionAuthFailureHandler.class);

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.info("[会话验证失败处理器] 会话验证失败,URI={}", request.getRequestURI());
        if (WebUtil.isAjaxRequest(request)) {
            WebUtil.write2Response(response, Result.error(ECommonResultCode.SESSION_TIMEOUT));
        } else {
            //请求的url
            response.sendRedirect("/login");
        }
    }
}
